<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Cache;
use think\helper\Hash;
use think\Db;
use app\common\builder\ZBuilder;
use app\user\model\User as UserModel;

/**
 * 后台默认控制器
 * @package app\admin\controller
 */
class Index extends Admin
{
    /**
     * 后台首页
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    public function index()
    {
        $admin_pass = Db::name('admin_user')->where('id', 1)->value('password');

        if (UID == 1 && $admin_pass && Hash::check('admin', $admin_pass)) {
            $this->assign('default_pass', 1);
        }
        return $this->fetch();
    }

    /**
     * 清空系统缓存
     * @author 蔡伟明 <314013107@qq.com>
     */
    public function wipeCache()
    {
        $wipe_cache_type = config('wipe_cache_type');
        if (!empty($wipe_cache_type)) {
            foreach ($wipe_cache_type as $item) {
                if ($item == 'LOG_PATH') {
                    $dirs = (array) glob(constant($item) . '*');
                    foreach ($dirs as $dir) {
                        array_map('unlink', glob($dir . '/*.log'));
                    }
                    array_map('rmdir', $dirs);
                } else {
                    array_map('unlink', glob(constant($item) . '/*.*'));
                }
            }
            Cache::clear();
            $this->success('清空成功');
        } else {
            $this->error('请在系统设置中选择需要清除的缓存类型');
        }
    }

    /**
     * 个人设置
     * @author 蔡伟明 <314013107@qq.com>
     */
    public function profile()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $data['nickname'] == '' && $this->error('昵称不能为空');
            $data['id'] = UID;

            // 如果没有填写密码，则不更新密码
            if ($data['password'] == '') {
                unset($data['password']);
            }

            $UserModel = new UserModel();
            if ($user = $UserModel->allowField(['nickname', 'email', 'password', 'mobile', 'avatar'])->update($data)) {
                // 记录行为
                action_log('user_edit', 'admin_user', UID, UID, get_nickname(UID));
                $this->success('编辑成功');
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = UserModel::where('id', UID)->field('password', true)->find();

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->addFormItems([ // 批量添加表单项
                ['static', 'username', '用户名', '不可更改'],
                ['text', 'nickname', '昵称', '可以是中文'],
                ['text', 'email', '邮箱', ''],
                ['password', 'password', '密码', '必填，6-20位'],
                ['text', 'mobile', '手机号'],
                ['image', 'avatar', '头像']
            ])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 检查版本更新
     * @author 蔡伟明 <314013107@qq.com>
     * @return \think\response\Json
     */
    public function checkUpdate()
    {
        $params = config('dolphin');
        $params['domain']  = request()->domain();
        $params['website'] = config('web_site_title');
        $params['ip']      = $_SERVER['SERVER_ADDR'];
        $params['php_os']  = PHP_OS;
        $params['php_version'] = PHP_VERSION;
        $params['mysql_version'] = db()->query('select version() as version')[0]['version'];
        $params['server_software'] = $_SERVER['SERVER_SOFTWARE'];
        $params = http_build_query($params);

        $opts = [
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_URL            => config('dolphin.product_update'),
            CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],
            CURLOPT_POST           => 1,
            CURLOPT_POSTFIELDS     => $params
        ];

        // 初始化并执行curl请求
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($data, true);

        if ($result['code'] == 1) {
            return json([
                'update' => '<a class="badge badge-primary" href="http://www.dolphinphp.com/download" target="_blank">有新版本：'.$result["version"].'</a>',
                'auth'   => $result['auth']
            ]);
        } else {
            return json([
                'update' => '',
                'auth'   => $result['auth']
            ]);
        }
    }
    
    
    //生成账号密码2000
    public function account_10000(){
        $characters = '0123456789';
        
        
        for($i=1;$i<10000;$i++){
            $data['account']="A".str_pad($i,7,"0",STR_PAD_LEFT);
            
            $randomString = '';
            for ($j = 0; $j < 6; $j++) {
                $randomString .= $characters[rand(0, strlen($characters) - 1)];
            }
            $data['psd']=$randomString;
            
          // db('account_psw')->insert($data);
            
        }
        
    }
    
    
    //已经支付用户列表
    public function users(){
        $map=$this->getMap();
        $data_list = Db::name('account_psw')
        ->where($map)
        ->paginate();
        
        session('map.user',$map);
        // 导出按钮
        $excel_out = [
            'title' => '导出列表数据',
            'icon'  => 'fa fa-fw fa-mail-forward',
            'href'  => url('excel_out'),
            'target'=>'_blank',
        ];

        // 导出按钮
        $message_out = [
            'title' => '发送短信',
            'icon'  => 'fa fa-fw fa-mail-forward',
            'class' => 'btn btn-xs btn-default ajax-get',
            'href'  => url('message_out',['id'=>'__id__']),
        ];

        $css = <<<EOF
           <style>
                .table-builder > tbody > tr > td{
                    white-space: normal;
                }
           </style>
EOF;

        // 分页数据
        $page = $data_list->render();
        return ZBuilder::make('table')
        ->setPageTitle('注册用户列表')
        ->setTableName('account_psw') // 指定数据表名
        ->setPrimaryKey('id')	//设置主键  //
        ->setSearch(['number'=>'订单编号','app_name' => '姓名','mobile' => '电话','unit' => '发票抬头','code' => '统一社会信用码','addres' => '地址','account' => '账号']) // 设置搜索参数
        ->hideCheckbox()
        ->addFilterList('is_message', ['未发送', '已发送']) // 添加筛选
        ->addColumns([ // 批量添加列
            ['number', '订单编号'],
            ['app_name', '姓名'],
            ['mobile', '收件人电话'],
            ['code', '统一社会信用码'],
            ['unit', '发票抬头'],
            ['addres', '地址'],
            ['account', '账号'],
            ['psd', '密码'],
            ['is_message', '是否发送','status', '', ['未发送', '已发送']],
        ])
        ->addColumn('right_button', '操作', 'btn')
        ->addTopButton('custom', $excel_out) // 添加导出按钮
        ->addRightButton('delete') // 添加任务开始按钮
        ->addRightButton('message',$message_out) // 添加任务开始按钮
        ->replaceRightButton(function ($data_list){
                return $data_list['mobile'] == '';
            }, '', 'message')
        ->setRowList($data_list) // 设置表格数据
        ->setExtraCss($css)
        ->setPages($page) // 设置分页数据
        ->fetch();
        
    }
    
    
    
    
    public function excel_out(){
        $map=session('map.user');
    
         $data_list = Db::name('account_psw')
        ->field("*,if(is_message,'是','否') is_message")
        ->where($map)
        ->select();
    //dump($data_list);die;
        $cellName=array(
            array('number','auto','订单编号'),
            array('app_name','auto','姓    名'),
            array('mobile','auto','收件人电话'),
            array('code','auto','统一社会信用码'),
            array('unit','auto','发票抬头'),
            array('addres','auto','地                址'),
            array('account','auto','账        号'),
            array('psd','auto','密     码'),
            array('is_message','auto','是否发送短信'),
        );
        plugin_action('Excel/Excel/export', ['用户数据'.date('Y-m-d_H_i_s',time()), $cellName, $data_list]);
        //var_dump($data);
    
    }

    public function message_out(){
        $id = $this->request->param('id',0);
        if($id == 0) $this->error('请选择用户');

        $info = db('account_psw')->where('id',$id)->find();
        if($info && !empty($info['mobile'])){
            $info['mobile'] = trim($info['mobile']);
            $mess = $this->sendsms($info['mobile'],$info['account'],$info['psd']);
            if($mess){
                db('account_psw')->where('id',$id)->update(['is_message'=>1]);
                $this->success('发送成功');
            }
        }else{
            $this->error('请选择正确用户');
        }

    }
    
    
    /*
     * 发送短信验证
     */
    public function sendsms($mobile='13880446756',$account='123',$psw="123456"){
        $product = '手机号码';
        $result = plugin_action('AliDayu/AliDayu/send', [[
            'param'  => ["account"=>$account,'psw'=>$psw,'product'=>$product],
            'mobile'  => $mobile,
        ]]);
        return $result;
    }
   
    
    
    
    
    
}